#pragma once 

#include <iostream>
#include <pthread.h>
#include <signal.h>
#include "TcpServer.hpp"
//#include "Protocol.hpp"
#include "log.hpp"
#include "ThreadPool.hpp"

#define PORT 8081

class HttpServer
{
  private:
    int port;
    //TcpServer *tcp_server;
    //ThreadPool thread_pool; 
    bool stop;
  public:
    //HttpServer(int _port = PORT):port(_port),tcp_server(nullptr),stop(false)
    HttpServer(int _port = PORT):port(_port),stop(false)
    {}

    void InitServer()
    {
      //信号SIGPIPE需要进行忽略，如果不忽略, 写入时候，服务器server会奔溃 
      signal(SIGPIPE, SIG_IGN);
      //tcp_server = TcpServer::getinstance(port);
    }

    void Loop()
    {
      TcpServer *tsvr = TcpServer::getinstance(port);
      LOG(INFO, "Loop begin");
      //int listen_sock = tcp_server->Sock();
      while(!stop)
      {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        //int sock = accept(listen_sock, (struct sockaddr*)&peer, &len);
        int sock = accept(tsvr->Sock(), (struct sockaddr*)&peer, &len);
        if(sock < 0)
        {
          continue;
        }
        LOG(INFO, "Get a new link");
        Task task(sock);
        ThreadPool::getinstance()->PushTask(task);

        //int *_sock = new int(sock);//暂时方案
        //pthread_t tid;
        //pthread_create(&tid, nullptr, Entance::HandlerRequest, _sock);
        //pthread_detach(tid);//线程分离
      }
    }

    ~HttpServer()
    {}

};
